import React, {Component} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {Card, Form, Input, Button, Select, Switch, Upload, Icon, Modal, message} from 'antd';
import {FormComponentProps} from 'antd/es/form';
import {Dispatch} from 'redux';
import {connect} from 'dva';
import ReactQuill from 'react-quill'; // ES6
import 'react-quill/dist/quill.snow.css';
import {UploadChangeParam} from "antd/lib/upload";
import {UploadFile} from "antd/lib/upload/interface";
import styles from './style.less';
import {IArticle} from "@/pages/articles/data";

const FormItem = Form.Item;
// const {RangePicker} = DatePicker;
// const {TextArea} = Input;

const {Option} = Select;
const formItemLayout = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 8},
    md: {span: 3},
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 12},
    md: {span: 18},
  },
};


const submitFormLayout = {
  wrapperCol: {
    xs: {span: 24, offset: 0},
    sm: {span: 10, offset: 3},
  },
};

interface Props extends FormComponentProps {
  submitting: boolean;
  dispatch: Dispatch<any>;
  location: any;
  articles: {
    articleDetail: IArticle,
    categoryList: any[]
  }
}

interface IState {
  previewImageUrl: string
  preViewModalVisible: boolean;
}

const modules = {
  toolbar: [
    [{'header': [1, 2, false]}],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
    ['link', 'image'],
    ['clean']
  ],
};

const formats = [
  'header',
  'bold', 'italic', 'underline', 'strike', 'blockquote',
  'list', 'bullet', 'indent',
  'link', 'image'
];

// const getBase64 = (file: File) => {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.readAsDataURL(file);
//     reader.onload = () => resolve(reader.result as string);
//     reader.onerror = error => reject(error);
//   });
// };


class Index extends Component<Props, IState> {

  state: IState = {
    previewImageUrl: '',
    preViewModalVisible: false,
  };

  componentDidMount() {
    console.log('componentDidMount');
    const {dispatch, location} = this.props;
    dispatch({
      type: 'articles/publishFetch',
      payload: {
        id: location.query.id || 0
      }
    })
  }

  // componentWillMount() {
  //   const {dispatch} = this.props;
  //   console.log('componentWillMount');
  // };

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const {form, dispatch, location} = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        values.thumb = values.thumb.map((item: any) => ({
          uid: item.uid,
          name: item.name,
          url: item.url ? item.url : item.response.data.file_url
        }));
        dispatch({
          type: 'articles/publishArticle',
          payload: {...values, id: (location.query.id || 0)}
        });
      }
    });
  };

  UploadButton = (
    <div>
      <Icon type='plus'/>
      {/*<Icon type={this.state.loading ? 'loading' : 'plus'}/>*/}
      <div className="ant-upload-text">图片上传</div>
    </div>
  );
  //UploadChangeParam
  handleUploadChange = (info: UploadChangeParam): any => {
    let fileList = info.fileList;
    if (info.file.status === 'done') {
      message.success(`${info.file.name}文件上传成功`);
    }
    return fileList.slice(-1);
  };

  //UploadFile
  photoPreview = (file: UploadFile) => {
    const fileUrl = file.url || file.thumbUrl;
    this.setState({
      previewImageUrl: (fileUrl as string),
      preViewModalVisible: true
    });
  };

  previewModalCancel = () => {
    this.setState({
      preViewModalVisible: false
    });
  };

  render() {
    const {
      form: {getFieldDecorator}, submitting, articles
    } = this.props;

    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Form onSubmit={this.handleSubmit}  {...formItemLayout}>
            <FormItem label="标题">
              {getFieldDecorator('title', {
                rules: [
                  {
                    required: true,
                    message: '标题不能为空',
                  },
                ],
                initialValue: articles.articleDetail.title
              })(<Input placeholder="请输入标题"/>)}
            </FormItem>
            <FormItem label="分类">
              {getFieldDecorator('category_id', {
                rules: [
                  {
                    required: true,
                    message: '请选择分类',
                    type: 'number',
                    min: 1
                  },
                ],
                initialValue: articles.articleDetail.category_id,
              })(
                <Select style={{width: 180}}>
                  <Option value={0}>请选择分类</Option>
                  {this.props.articles.categoryList.map((item: any) => {
                    return (<Option key={item.id} value={item.id}>{item.title}</Option>)
                  })}
                </Select>
              )}
            </FormItem>

            <FormItem label="标签">
              {getFieldDecorator('labels', {
                rules: [
                  {
                    required: true,
                    message: '请输入至少一个标签',
                  },
                ],
                initialValue: articles.articleDetail.labels
              })(
                <Select mode="tags" style={{width: '100%'}} placeholder="请输入标签">

                </Select>
              )}
            </FormItem>

            <FormItem label="状态">
              {
                getFieldDecorator('status', {
                  rules: [
                    {
                      required: true
                    },
                  ],
                  valuePropName: 'checked',
                  initialValue: !!articles.articleDetail.status

                })(<Switch checkedChildren="启用" unCheckedChildren="禁用"/>)
              }
            </FormItem>

            <FormItem label="缩略图">

              {
                getFieldDecorator('thumb', {
                  rules: [
                    {
                      required: true,
                      message: '请先上传图片'
                    }
                  ],
                  getValueFromEvent: this.handleUploadChange,
                  valuePropName: 'fileList',
                  initialValue: articles.articleDetail.thumb,
                })(
                  <Upload
                    listType="picture-card"
                    accept=".jpg,.jpeg,.png"
                    action="http://106.13.168.150:9501/upload/photo"
                    name="photo"
                    showUploadList={{showPreviewIcon: true, showRemoveIcon: true}}
                    // onChange={this.handleUploadChange}
                    onPreview={this.photoPreview}
                    // fileList={this.state.fileList}
                    className={styles.uploadListInline}
                  >
                    {/*{this.props.form.getFieldValue('thumb').length > 1 ? null : this.UploadButton}*/}
                    {this.UploadButton}

                  </Upload>
                )
              }
              <Modal visible={this.state.preViewModalVisible} footer={null} onCancel={this.previewModalCancel}>
                <img alt="example" style={{width: '100%'}} src={this.state.previewImageUrl}/>
              </Modal>
            </FormItem>
            <FormItem label="内容">
              {
                getFieldDecorator('content', {
                  rules: [
                    {
                      required: true,
                      message: '请输入内容',
                    },
                  ],
                  initialValue: articles.articleDetail.content
                })(
                  <ReactQuill theme="snow" modules={modules} formats={formats} style={{height: 350, lineHeight: 1}}/>
                )
              }
            </FormItem>

            <FormItem {...submitFormLayout} style={{marginTop: 50}}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                提交
              </Button>
              {/*<Button style={{marginLeft: 8}}>保存</Button>*/}
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<Props>()(
  connect(({articles, loading}: {
    articles: {
      articleDetail: IArticle,
      categoryList: any[]
    }, loading: { effects: { [key: string]: boolean } }
  }) => ({
    submitting: loading.effects['articles/publishArticle'],
    articles
  }))(Index),
);
